/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spelet;

import java.util.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Editor extends Canvas {

    public static int square = 40;
    public int dir = 1;
    public int tiles=6;
    public int tileIndex = 1;
    public int groupIndex=0;
    public int entityGarbage=0;
    public int orginalSize;
    private BufferStrategy strategy;
    private boolean gameRunning = true;
    private boolean blockMode = false;
    private boolean firstEnter = true;
    boolean leftPressed;
    boolean rightPressed;
    boolean upPressed;
    boolean downPressed;
    boolean xPressed;
    boolean zPressed;
    boolean sPressed;
    boolean spacePressed;
    boolean enterPressed;
    boolean controlPressed;
    boolean keyAction = false;
    boolean editor = true;
    String lvl = "editor";


    public Editor() {
        JFrame container = new JFrame();

        JPanel panel = (JPanel) container.getContentPane();
        panel.setPreferredSize(new Dimension(800, 600));
        panel.setLayout(null);
        setBounds(0, 0, 800, 600);
        panel.add(this);

        setIgnoreRepaint(true); //Säger till awt att inte måla om canvasen,
        //eftersom vi gör de i "accelerated mode"
        container.pack();
        container.setResizable(false);
        container.setVisible(true);

        //Låter awt att använda accelerarad grafik
        createBufferStrategy(2);
        strategy = getBufferStrategy();

        addKeyListener(new KeyInputHandler());
        requestFocus();
    }

    public void gameLoop() {

        long lastLoopTime = System.currentTimeMillis();

        java.util.List<Entity> entities = new ArrayList<Entity>();
        java.util.List<Entity> blocks = new ArrayList<Entity>();
        java.util.List<Entity> temp = new ArrayList<Entity>();

        entities.add(new Spawn(400, 560,560));


        while (gameRunning) {
            long delta = System.currentTimeMillis() - lastLoopTime;
            lastLoopTime = System.currentTimeMillis();

            Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
            g.setColor(Color.black);
            g.fillRect(0, 0, 800, 600);

            /////////////////////////////////////
            int activeEnt=entities.size() - 1;
            int activeEntX=entities.get(activeEnt).position_x;
            int activeEntY=entities.get(activeEnt).position_y;
            int activeEntScroll=entities.get(activeEnt).scrollPosition;
            //////////////////////////////////////////////////////

            //Knappskit
            //////////////////////////////////////////////////////////////
            if ((upPressed) && (!downPressed) && (!keyAction)) {
                dir=1;
                entities.get(activeEnt).moveY(-square);
                entities.get(activeEnt).scrollPosition =
                        entities.get(activeEnt).scrollPosition - square;
                keyAction = true;
            }
            else if ((leftPressed) && (!rightPressed) && (!keyAction) &&
                    activeEntX != 0) {

                entities.get(activeEnt).moveX(-square);
                keyAction = true;
            }
            else if ((downPressed) && (!upPressed) && (!keyAction) &&
                    activeEntScroll != 560) {
                dir=-1;
                entities.get(activeEnt).moveY(square);
                entities.get(activeEnt).scrollPosition =
                        entities.get(activeEnt).scrollPosition +
                        square;
                keyAction = true;
            }
            else if ((rightPressed) && (!leftPressed) && (!keyAction) &&
                    activeEntX != 760) {

                entities.get(activeEnt).moveX(square);
                keyAction = true;
            }
            else if ((spacePressed) && (!keyAction)) {
                if(tileIndex==1){
                    //I blockbyggar-läget ska objekten sparas i "blocks"!
                    if(blockMode==true){
                       blocks.add(new Rust(activeEntX,activeEntY,activeEntScroll));
                       blocks.get(blocks.size()-1).group=groupIndex;

                   }
                    entities.add(new Rust(activeEntX,activeEntY,activeEntScroll));
                }
                else if(tileIndex==2){
                    if(blockMode==true){
                       blocks.add(new Tnt(activeEntX,activeEntY,activeEntScroll));
                       blocks.get(blocks.size()-1).group=groupIndex;

                   }
                    entities.add(new Tnt(activeEntX,activeEntY,activeEntScroll));
                }
                else if(tileIndex==3){
                    if(blockMode==true){
                        erase(blocks);
                    }
                    erase(entities);

                }
                else if(tileIndex==4){

                    entities.add(new Brick(activeEntX,activeEntY,activeEntScroll));
                }
                else if(tileIndex==5){
 
                    entities.add(new Spawn(activeEntX,activeEntY,activeEntScroll));
                }


                keyAction = true;
            }
            else if((xPressed) && (!zPressed) && (!keyAction)){
                nextTile(entities,1);
                keyAction = true;
            }
            else if((zPressed) && (!xPressed) && (!keyAction)){
                nextTile(entities,-1);
                keyAction = true;

            }
            else if((controlPressed) && (sPressed) && (!keyAction)){
                levelSave(temp);
                keyAction=false;
                controlPressed=false;
                sPressed=false;
            }
            //Frågar om du vill gå till blockbyggarläge
            else if((enterPressed) && (!keyAction) && (blockMode==false)){
                if(confirm("Are you sure you want to go to block buildning mode?",
                        "Block buildning mode?")==true){
                    //Sparar senast liststorlek för entities!
                    orginalSize=entities.size();
                    //gör en kopia av entities
                    temp= new ArrayList<Entity>(entities);
                    //sätter inga block då du inte gjort dom, men fixar så att man får rätt verktyg osv
                    setBlocks(entities,blocks);
                    blockMode=true;
                }
                keyAction=false;
                enterPressed=false;
                
            }
            //Om du är i blockbyggar läget "sparar" den block du byggt varje gång du
            //trycker ENTER!
            else if((enterPressed) && (!keyAction) && (blockMode==true)){
                keyAction = true;
                setBlocks(entities,blocks);
            }


////////////////////////////////////////////////////////////////////////////////////
            //Städar upp objekt som ligger på varandra
            tileCleanup(entities);
            tileCleanup(blocks);
            

            //Skrollar skärmen om man fyttat "markören"
            scroll(entities);
            //ritar  ut alla entitys
            for (Entity f : entities) {
                f.draw(g);
            }
            //Skriver ut x,y-koordinater + rikting
            //System.out.println(entities.get(entities.size() - 1).position_x +
              //      " " + entities.get(entities.size() - 1).scrollPosition);
            //System.out.println(dir);
            //System.out.println(entities.size());
            ////////////////////
            g.dispose();
            strategy.show();
            try {
                Thread.sleep(10);
            } catch (Exception e) {
            }
            

        }
    }

    public static void main(String argv[]) {
        Game g = new Game();
        g.gameLoop();
    }
    //Dialogruta med ja,nej alternativ
    private boolean confirm(String message,String title){

    // display the JOptionPane showConfirmDialog
    int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
    if (reply == JOptionPane.YES_OPTION){
      return true;
    }
    else{
      return false;
    }
    }
    //Scrollar skärmen om den aktiverade tilen är påväg utanför skärmen
    private void scroll(java.util.List<Entity> entities) {
        if (entities.get(entities.size() - 1).position_y < 0 ||
                entities.get(entities.size() - 1).position_y > 560) {
            for (Entity f : entities) {
                f.scrollPosition = f.scrollPosition + (-dir * square);
                f.moveY(square*dir);
            }
        }
    }
    //Växlar tile
    private void nextTile(java.util.List<Entity> entities,int direction) {
        int x;
        int y;
        int scrollY;

        x=entities.get(entities.size()-1).position_x;
        y=entities.get(entities.size()-1).position_y;
        scrollY=entities.get(entities.size()-1).scrollPosition;
        entities.remove(entities.size()-1);

        //tileIndex blir antingen +1 eller -1, beroende på vilket håll du växlar
        //sprites åt.
        tileIndex=tileIndex+direction;
        
        if(tileIndex==0){
            tileIndex=tiles;
        }
        else if(tileIndex>tiles){
            tileIndex=1;
        }

        if (tileIndex==1){
            entities.add(new Rust(x,y,scrollY));
        }
        else if(tileIndex==2){
            entities.add(new Tnt(x,y,scrollY));
        }
        else if(tileIndex==3){
            entities.add(new Eraser(x,y,scrollY));
        }
        else if(tileIndex==4){
            entities.add(new Brick(x,y,scrollY));
        }
        else if(tileIndex==5){
            entities.add(new Spawn(x,y,scrollY));
        }
        else if(tileIndex==6){
            entities.add(new NewBlock(x,y,scrollY));
        }
    }
    //Tar bort tiles som ligger under andra tiles
    private void tileCleanup(java.util.List<Entity> list){
        for (int i = 0; i < list.size()-1; i++) {
            for (int j = i+1; j < list.size()-1; j++) {
                if (list.get(i).collisionBox().intersects(list.get(j).collisionBox())) {
                    list.remove(i);
                    entityGarbage--;

                }
            }
        }

    }
    //Tar bort block med ett suddi
    private void erase(java.util.List<Entity> list){
        for (int i=0;i<list.size()-1; i++){
            if (list.get(list.size()-1).collisionBox().intersects(list.get(i).collisionBox())){
                list.remove(i);
            }
        }
    }

    private void setBlocks(java.util.List<Entity> entities,java.util.List<Entity> blocks){
        //antalet tiles(från 1-tiles) som ska vara tillgängliga i blockMode
        tiles=3;
        //Nästa grupp kommer att få ett indexnummer över föregångarna
        groupIndex++;

        //kollar hur många entities som skapats utöver det som fanns innan
        //blockMode, sparas i denna "sophög"
        entityGarbage=entities.size()-orginalSize;
        
        //Tar bort entities som satts ut under föregångna blockbygge
        for(int i=entityGarbage; i>0;i--){
            entities.remove(entities.size()-1);
        }
        ///////////////////////////
        tileIndex=tiles;
        nextTile(entities,1);
        for (Entity f : blocks) {
            System.out.println(f.type);
        }
    }

    //Sparar banan i vald textfil
    private void levelSave(java.util.List<Entity> entities) {
        String mapName;
        mapName = JOptionPane.showInputDialog(null, "Mapname?");


        if (mapName != null && !mapName.isEmpty()) {
            if (entities.size() != 0) {
                try {
                    //Ny mapp!
                    (new File("maps")).mkdir();
                    FileWriter fstream = new FileWriter("maps\\"+mapName + ".txt");
                    BufferedWriter out = new BufferedWriter(fstream);
                    out.write(mapName + "\r\n");
                    for (int i = 0; i < entities.size()- 1; i++) {
                        out.write(entities.get(i).type + " " + entities.get(i).position_x +
                                " " + entities.get(i).position_y + "\r\n");
                    }
                    //Close the output stream
                    out.close();
                } catch (Exception e) {//Catch exception if any
                    System.err.println("Error: " + e.getMessage());
                }
            }
        }
    }

    

/////////////////////////////////////////////////////////////

    class KeyInputHandler extends KeyAdapter {

        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                leftPressed = true;
            }

            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                rightPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                upPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                downPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_X) {
                xPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_Z) {
                zPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_S) {
                sPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                spacePressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                enterPressed = true;
            }
            if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
                controlPressed = true;
            }
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                leftPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                rightPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                upPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                downPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_X) {
                xPressed = false;
                keyAction = false;

            }
            if (e.getKeyCode() == KeyEvent.VK_Z) {
                zPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_S) {
                sPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                spacePressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                enterPressed = false;
                keyAction = false;
            }
            if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
                controlPressed = false;
                keyAction = false;
            }

        }

        public void keyTyped(KeyEvent e) {
            // if we hit escape, then quit the game
            if (e.getKeyChar() == 27) {
                System.exit(0);
            }
        }
    }
}



